package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.topscore.uke.R;
import com.topscore.uke.database.entities.SearchHistoryItem;
import com.topscore.uke.entities.HotWordItem;
import com.topscore.uke.mvp.contractors.GetHotWordContractor;
import com.topscore.uke.mvp.contractors.SearchHistoryContractor;
import com.topscore.uke.mvp.presenters.GetHotWordPresenter;
import com.topscore.uke.mvp.presenters.SearchHistoryPresenter;
import com.topscore.uke.ui.BaseCompatActivity;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.ui.widgets.DividerGridItemDecoration;
import com.topscore.uke.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SearchActivity extends BaseCompatActivity implements GetHotWordContractor.View, SearchHistoryContractor.View {

    @Bind(R.id.search_edt)
    EditText searchEdt;
    @Bind(R.id.tool_bar)
    Toolbar toolBar;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    private final int _Item_HotSearch = 1001;
    private final int _Item_SearchHistory = 1002;

    private RecyclerView mHotSearchRecycler, mHistoryRecycler;

    private List<MultiItem> mMultiItemList;
    //    List<String> titles = new ArrayList<>();
    private GetHotWordPresenter mHotWordPresenter;
    private SearchHistoryPresenter mHistoryPresenter;

    private BaseQuickAdapter<HotWordItem, BaseViewHolder> mHotSearchAdapter;
    private BaseQuickAdapter<SearchHistoryItem, BaseViewHolder> mHistoryAdapter;

    private MultiAdapter mMultiAdapter;
    private View mEmptyHistoryView;

    private LoadService mLoadService;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commodity_search, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.action_search:
//                toSearchResult();
                String word = searchEdt.getText().toString();
                if (!StringUtil.isEmpty(word)) {
                    toSearchResult(word);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void toSearchResult(String word) {
        mHistoryPresenter.insertSearchWord(word);
        Intent intent = new Intent(this, SearchResultActivity.class);
        intent.putExtra("search_word", word);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        toolBar.setTitle("");
        setSupportActionBar(toolBar);
        initViews();
    }

    private void initViews() {
        initMultiAdapter();
        searchEdt.setOnEditorActionListener(((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                String word = searchEdt.getText().toString();
                toSearchResult(word);
                return true;
            }
            return false;
        }));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mMultiAdapter);
        mHotWordPresenter = new GetHotWordPresenter(this);
        mHistoryPresenter = new SearchHistoryPresenter(this);
    }

    private void initMultiAdapter() {
//        initHotSearchList();
        mMultiItemList = new ArrayList<>();
        mMultiItemList.add(new MultiItem(_Item_HotSearch));
        mMultiItemList.add(new MultiItem(_Item_SearchHistory));
        mMultiAdapter = new MultiAdapter(mMultiItemList);
    }

    @Override
    public void onLoading(String loadingMessage) {
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(ErrorCallBack.class);
    }

    @Override
    public BaseQuickAdapter getWordsAdapter() {
        return mHotSearchAdapter;
    }

    @Override
    public BaseQuickAdapter getRecyclerAdapter() {
        return mHistoryAdapter;
    }

//    private void initHotSearchList() {
//        titles.add("小白鞋");
//        titles.add("凉鞋");
//        titles.add("高跟鞋");
//        titles.add("帆布鞋");
//        titles.add("818专场");
//        titles.add("单鞋");
//        titles.add("2017秋季新品");
//    }

    private class MultiItem implements MultiItemEntity {

        private int itemType;

        private MultiItem(int itemType) {
            this.itemType = itemType;
        }

        @Override
        public int getItemType() {
            return itemType;
        }
    }

    private Handler searchHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            String word = message.getData().getString("search_word");
            toSearchResult(word);
            return false;
        }
    });

    private Bundle mSearchWordBundle;
    private Message mSearchMessage;

    private class MultiAdapter extends BaseMultiItemQuickAdapter<MultiItem, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        public MultiAdapter(List<MultiItem> data) {
            super(data);
            addItemType(_Item_HotSearch, R.layout.popular_search_layout);
            addItemType(_Item_SearchHistory, R.layout.search_history_layout);
        }

        @Override
        protected void convert(BaseViewHolder holder, MultiItem item) {
            switch (item.getItemType()) {
                case _Item_HotSearch:
                    mHotSearchRecycler = holder.getView(R.id.popular_search_recycler);
                    FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(mContext, FlexDirection.ROW);
                    flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
//                    flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
                    mHotSearchRecycler.setLayoutManager(flexboxLayoutManager);
                    mHotSearchRecycler.addItemDecoration(new DividerGridItemDecoration(mContext, R.drawable.stuff_grid_decoration));
                    mHotSearchAdapter = new BaseQuickAdapter<HotWordItem, BaseViewHolder>(R.layout.hot_search_item, new ArrayList<>()) {
                        @Override
                        protected void convert(BaseViewHolder helper, HotWordItem item) {
                            helper.setText(R.id.item_title, item.getName());
                            helper.getConvertView().setOnClickListener(view -> {
                                mSearchWordBundle = new Bundle();
                                mSearchWordBundle.putString("search_word", item.getName());
                                mSearchMessage = new Message();
                                mSearchMessage.setData(mSearchWordBundle);
                                searchEdt.setText(item.getName());
                                searchHandler.sendMessageDelayed(mSearchMessage, 100);
                            });
//                            ViewGroup.LayoutParams lp = helper.getConvertView().getLayoutParams();
//                            if (lp instanceof FlexboxLayoutManager.LayoutParams) {
//                                FlexboxLayoutManager.LayoutParams flexboxLp =
//                                        (FlexboxLayoutManager.LayoutParams) helper.getConvertView().getLayoutParams();
//                                flexboxLp.setFlexGrow(7.0f);
//                            }
                        }
                    };

                    mHotSearchRecycler.setAdapter(mHotSearchAdapter);
                    mLoadService = LoadSir.getDefault().register(mHotSearchRecycler, v -> {
                    });
                    mHotWordPresenter.getHotWord();
                    break;

                case _Item_SearchHistory:
                    mHistoryRecycler = holder.getView(R.id.history_search_recycler);
                    mHistoryRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
                    mHistoryAdapter = new BaseQuickAdapter<SearchHistoryItem, BaseViewHolder>(R.layout.search_history_item, new ArrayList<>()) {
                        @Override
                        protected void convert(BaseViewHolder helper, SearchHistoryItem item) {
                            helper.setText(R.id.item_title, item.getWord());
                            helper.getConvertView().setOnClickListener(view -> {
                                mSearchWordBundle = new Bundle();
                                mSearchWordBundle.putString("search_word", item.getWord());
                                mSearchMessage = new Message();
                                mSearchMessage.setData(mSearchWordBundle);
                                searchEdt.setText(item.getWord());
                                searchHandler.sendMessageDelayed(mSearchMessage, 100);
                            });
                        }
                    };
                    mEmptyHistoryView = getLayoutInflater().inflate(R.layout.search_history_empty, (ViewGroup) mHistoryRecycler.getParent(), false);
                    mHistoryAdapter.setEmptyView(mEmptyHistoryView);
                    mHistoryRecycler.setAdapter(mHistoryAdapter);
                    mHistoryPresenter.getSearchHistory();
                    break;

            }
        }
    }

}
